package utils
{
	public class RegUtil
	{
		public function RegUtil()
		{
			//Test
			var content:String = "abababaaaabbbaba";
			var reg:RegExp = /ab/g;
			trace(bothEnds(content,reg,"<",">"));
		}
		
		/**
		 * 左端插入
		 */
		public static function insertLeft(content:String,reg:RegExp,left:String):String
		{
			return bothEnds(content,reg,left,"");
		}
		
		/**
		 * 右端插入
		 */
		public static function insertRight(content:String,reg:RegExp,right:String):String
		{
			return bothEnds(content,reg,"",right);
		}
		
		/**
		 * 两端插入
		 */
		public static function bothEnds(content:String,reg:RegExp,left:String,right:String):String
		{
			function leftAndRight(match:String):String
			{
				return left+match+right;
			}
			return exec(content,reg,leftAndRight);
		}
		
		/**
		 * 执行匹配可以迭代多次进行匹配处理
		 */
		public static function exec(content:String,reg:RegExp,iterator:Function):String
		{
			if(iterator==null) return content;
			reg.lastIndex=0;
			var keys:Array = [];
			var strs:Array = [];
			while(true){
				var result:* = reg.exec(content);
				if(result){
					keys.push(result.index,reg.lastIndex);	
				}
				else{
					break;
				}
			}
			
			keys.push(content.length);
			
			var start:int = 0;var end:int=0;
			for(var i:int=0;i<keys.length;i++){
				end = keys[i];
				var str:String = content.substring(start,end);
				strs.push(str);
				start=end;
			}
			
			for(i=1;i<strs.length;i+=2){
				strs[i] = iterator(strs[i]);
			}
			var newContent:String = strs.join("");
			return newContent;
		}
		
		/**
		 * 执行匹配可以迭代多次进行匹配处理
		 */
		public static function exec2(content:String,reg:RegExp,iterator:Function):String
		{
			if(iterator==null) return content;
			reg.lastIndex=0;
			var keys:Array = [];
			var strs:Array = [];
			while(true){
				var result:* = reg.exec(content);
				if(result){
					keys.push(result.index,reg.lastIndex);	
				}
				else{
					break;
				}
			}
			
			keys.push(content.length);
			
			var start:int = 0;var end:int=0;
			for(var i:int=0;i<keys.length;i++){
				end = keys[i];
				var str:String = content.substring(start,end);
				strs.push(str);
				start=end;
			}
			
			for(i=1;i<strs.length;i+=2){
				strs[i] = iterator(strs[i-1],strs[i],strs[i+1]);
			}
			var newContent:String = strs.join("");
			return newContent;
		}
	}
}